package com.lgCore.serverHandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.lgCore.common.LocalSession;
import com.lgCore.common.SessionManger;
import com.lgCore.nettyCocurrent.ExecutorScheduler;
import com.lgCore.protoModel.ProtoMsg;
import com.lgCore.serverProcesser.ServiceInvokCallable;
import com.lgCore.serverProcesser.ServiceInvokCallable;
import io.netty.channel.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

//@Slf4j
//@Service("ChatRedirectHandler")
public class RpcHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(RpcHandler.class);

    /**
     * 收到消息
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
//        log.info( "接受rpc数据"+ msg);
        //判断消息实例
        if (null == msg || !(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }
        ProtoMsg.Message message = (ProtoMsg.Message) msg;
        //取得请求类型
        ProtoMsg.RpcRequest rpcRequest = message.getRpcRequest();
        if (!rpcRequest.getType().equals(ProtoMsg.HeadType.RPC_REQUEST)) {
            super.channelRead(ctx, msg);
            return;
        }

        //异步处理转发的逻辑
//        FutureTaskScheduler.add(() ->
//        {
        //判断是否登录
        LocalSession session = SessionManger.get(rpcRequest.getClientId());
//            if (null != session && session.isLogin()) {
//                return;
//            }
        if (null == session) {
            return;
        }
//            log.info("收到客户端消息："+rpcRequest);
        //执行任务
        ExecutorScheduler.add(new ServiceInvokCallable(message,session));
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx)
            throws Exception {
        //channel失效，从Map中移除
        Channel channel = ctx.channel();
        ChannelId channelId = channel.id();
        String idStr = channelId.asLongText();
        LOGGER.info("服务端与客户端断开连接:" + idStr);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // ..

        //捕捉异常信息
        cause.printStackTrace();
        ctx.close();


    }
}
